package com.yuntai.pms.model.param;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: GridUtil
 * @Description: TODO
 * @author wangze@hsyuntai.com
 * @date 2017年8月1日 下午9:45:51
 */
public class GridUtil {

    static final int MAX_ID_LENGTH = 3;
    static int       temp;

    public static GridRows getGridList(List<Map<String, Object>> rsList, String[] paramSerial, int offset, int pageSize, long total,
                                       boolean isCheckBox) {
        GridRows nows = new GridRows();
        if (rsList == null || paramSerial == null || rsList.isEmpty() || paramSerial.length == 0) {
            return nows;
        }
        List<GridModel> list = new ArrayList<GridModel>();
        GridModel model = null;
        for (Map<String, Object> map : rsList) {
            String nextid = nextid();
            model = new GridModel();
            model.setId(nextid);
            model.setData(getDataforMap(isCheckBox, nextid, map, paramSerial));
            list.add(model);
        }
        nows.setPos(offset);
        nows.setTotal_count((int) total < pageSize ? (int)total : (int)total);
        nows.setRows(list);
        return nows;
    }

    /**
     * 非分页
     *
     * @param rsList
     * @param paramSerial
     * @param isCheckBox
     * @return
     */
    public static GridRows getGridList(List<Map<String, Object>> rsList, String[] paramSerial, boolean isCheckBox) {
        GridRows nows = new GridRows();
        if (rsList == null || paramSerial == null || rsList.isEmpty() || paramSerial.length == 0) {
            return nows;
        }
        List<GridModel> list = new ArrayList<GridModel>();
        GridModel model = null;
        for (Map<String, Object> map : rsList) {
            String nextid = nextid();
            model = new GridModel();
            model.setId(nextid);
            model.setData(getDataforMap(isCheckBox, nextid, map, paramSerial));
            list.add(model);
        }
        nows.setPos(0);
        nows.setTotal_count(list.size());
        nows.setRows(list);
        return nows;
    }

    private static List<String> getDataforMap(boolean isCheckBox, String nextid, Map<String, Object> map, String[] paramSerial) {
        List<String> data = new ArrayList<String>();
        if (isCheckBox) {
            data.add(nextid);
        }
        for (String col : paramSerial) {
            Object obj = map.get(col);
            data.add(obj != null ? obj.toString() : "");
        }
        return data;
    }

    public static String nextid() {
        temp = temp >= Integer.MAX_VALUE ? 0 : ++temp;
        String s = String.valueOf(temp);
        if (s.length() <= MAX_ID_LENGTH) {
            char[] ary1 = String.valueOf(temp).toCharArray();
            char[] ary2 = { '0', '0', '0', '0' };
            System.arraycopy(ary1, 0, ary2, ary2.length - ary1.length, ary1.length);
            return new String(ary2);
        }
        return s;
    }

}
